package com.ruoyi.manage.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.ruoyi.manage.domain.MusicSongpages;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.manage.service.IMusicSongsService;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Base64;


/**
 * 歌曲详细信息Controller
 *
 * @author xiaoshier
 * @date 2024-07-29
 */
@RestController
@RequestMapping("/musicPage/songpages")
public class MusicSongpagesController extends BaseController {
    @Autowired
    private IMusicSongsService musicSongsService;

    @PreAuthorize("@ss.hasPermi('musicPage:songpages:query')")
    @GetMapping(value = "/{musicSongpagesId}")
    public AjaxResult getpageInfo(@PathVariable("musicSongpagesId") Long musicSongpagesId) {
        List<MusicSongpages> list = musicSongsService.selectMusicSongpage(musicSongpagesId);
        List<String> base64Strings = new ArrayList<>();
        for (MusicSongpages item : list) {
            String pageUrl = item.getPageUrl(); // 直接调用getter方法
            String base64Str = convertImageToBase64Str(pageUrl);
            base64Strings.add(base64Str);
        }
        return success(base64Strings);

    }
    /**
     * 图片转Base64字符串
     * @param imageFileName
     * @return
     */
    public static String convertImageToBase64Str(String imageFileName) {
        ByteArrayOutputStream baos = null;
        try {
            //获取图片类型
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            //构建文件
            File imageFile = new File(imageFileName);
            //通过ImageIO把文件读取成BufferedImage对象
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            //构建字节数组输出流
            baos = new ByteArrayOutputStream();
            //写入流
            ImageIO.write(bufferedImage, suffix, baos);
            //通过字节数组流获取字节数组
            byte[] bytes = baos.toByteArray();
            //获取JDK8里的编码器Base64.Encoder转为base64字符
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



}
